const fs = require('fs');
const path = require('path');

/**
 * 将时间戳字段改回使用@Column，但使用更兼容的语法
 */
function revertToColumnTimestamps() {
    console.log('🔧 将时间戳字段改回使用@Column...');

    const entitiesDir = path.join(__dirname, 'nestjs-app/src/entities');
    const files = fs.readdirSync(entitiesDir).filter(file => file.endsWith('.entity.ts'));

    let fixedCount = 0;

    for (const file of files) {
        const filePath = path.join(entitiesDir, file);
        let content = fs.readFileSync(filePath, 'utf8');
        let modified = false;

        // 检查是否包含@CreateDateColumn或@UpdateDateColumn
        if (content.includes('@CreateDateColumn') || content.includes('@UpdateDateColumn')) {
            console.log(`📝 修复文件: ${file}`);

            // 替换@CreateDateColumn
            content = content.replace(
                /@CreateDateColumn\(\{\s*name:\s*"created_at",\s*comment:\s*"创建时间"\s*\}\)\s*created_at!:\s*Date;/g,
                '@Column("datetime", { name: "created_at", comment: "创建时间" })\n  created_at!: Date;'
            );

            // 替换@UpdateDateColumn
            content = content.replace(
                /@UpdateDateColumn\(\{\s*name:\s*"updated_at",\s*comment:\s*"更新时间"\s*\}\)\s*updated_at!:\s*Date;/g,
                '@Column("datetime", { name: "updated_at", comment: "更新时间", nullable: true })\n  updated_at!: Date | null;'
            );

            // 移除不需要的导入
            if (content.includes('@CreateDateColumn') || content.includes('@UpdateDateColumn')) {
                // 如果还有其他CreateDateColumn或UpdateDateColumn，保留导入
            } else {
                // 移除CreateDateColumn和UpdateDateColumn的导入
                content = content.replace(
                    /,\s*CreateDateColumn,?\s*/g,
                    ', '
                );
                content = content.replace(
                    /,\s*UpdateDateColumn,?\s*/g,
                    ', '
                );
                content = content.replace(
                    /CreateDateColumn,\s*/g,
                    ''
                );
                content = content.replace(
                    /UpdateDateColumn,\s*/g,
                    ''
                );
                // 清理多余的逗号
                content = content.replace(/,\s*}/g, ' }');
                content = content.replace(/{\s*,/g, '{ ');
            }

            if (modified) {
                fs.writeFileSync(filePath, content, 'utf8');
                fixedCount++;
                console.log(`✅ 已修复: ${file}`);
            }
        }
    }

    console.log(`🎉 修复完成！共修复了 ${fixedCount} 个文件`);
}

// 执行修复
revertToColumnTimestamps();
